import Moon from '../moon';
import { parseQuery } from '../util/h5';
// const history = window.history;
// const document = window.document;
// 延长1.5秒，防止快速跳转页面算入统计量
const delayTime = 1200;
// 自定义事件
const customEventName = 'moonhashchange';
let delayObj;

function _CustomEvent(customEventName, data) {
  let customEvent
  if (window['CustomEvent']) {
    customEvent = new CustomEvent(customEventName, {
      detail: data
    })
  } else {
    customEvent = document.createEvent('HTMLEvents')
    customEvent.initEvent(customEventName, !1, !0)
    customEvent.detail = data
  }
  window.dispatchEvent(customEvent)
}

function filter_pvUv(data?: any, extra = {}) {
  delayObj && clearTimeout(delayObj);
  var stateUrl = data.detail || data.newURL || '';
  var query: any = parseQuery(stateUrl);
  if (query.logtype) {
    query.area = query.logtype;
    delete query.logtype;
  } else {
    query = {}
  }
  delayObj = setTimeout(() => {
    Moon.logger({
      t: 'pu',
      ...extra,
      ...query,
    });
  }, delayTime);
}

window.addEventListener('load', function () {
  const data: any = {
    t: 'pu'
  }
  try {
    // 页面加载时间
    const _pNav = performance.getEntriesByType('navigation')[0]
    data.lt = (_pNav['responseEnd'] - _pNav['fetchStart']).toFixed(2)
    // 环境 ali支付宝 ding钉钉 wct微信 
    //data.ue = userBase.ue
    // 必要文件加载是否正常
    // const _pRes = performance.getEntriesByType('resource') || []
    // for (let i = 0; i < _pRes.length; i++) {
    //   const res: any = _pRes[i];
    //   if (res.initiatorType === "script") {
    //     for (let j = 0; j < file.length; j++) {
    //       const f = file[j];
    //       if (res.name.indexOf(f) > -1) {
    //         file.splice(j, 1)
    //         break;
    //       }
    //     }
    //   }
    // }
    // if (file.length) data.fl = file.join(',')
  } catch (e) { }
  filter_pvUv({detail: window.location.href}, data)
}, false)


export default function initPuv() {
  if (Moon.spa) {
    ['pushState', 'replaceState'].forEach(function (val) {
      const fun = history[val]
      history[val] = function (query, title, url) {
        const params = Array.apply(null, arguments)
        const href = location.href
        fun.apply(history, params)
        if (typeof url !== "string" || url === href) return
        _CustomEvent(customEventName, url)
      }
    })
    window.addEventListener(customEventName, filter_pvUv, false)
    window.addEventListener('hashchange', filter_pvUv, false)
  }
}